package com.zdj.collection;

import com.google.common.collect.Lists;
import com.zdj.model.User;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhangdj
 * @date 2022-07-22
 * com.google.common.collect.Lists#transform(java.util.List, com.google.common.base.Function)
 * 有坑，该方法返回的list不能遍历赋值，而且对原list改变会影响新list
 */
public class ListsTest {

    private static List<User> list;

    static {
        list = new ArrayList<>();
        User realUser = new User(1L, "zhang");
        list.add(realUser);
    }

    @Test
    public void normalList() {
        User user = new User(1L, "zhang");
        list.add(user);
        for (User item : list) {
            item.setId(2L);
        }
    }

    @Test
    public void transformingRandomAccessList() {
        User user = new User(2L, "zhang");
        list.add(user);
        List<User> users = Lists.transform(list, e-> new User(e.getId(), e.getName()));
        // 用迭代器next()的时候会用原对象转换出新的对象，所以对原来的list修改会影响新的list
        for (User item : users) {
            item.setId(777L);
        }

        // 遍历 每次get的都是新对象
        for (int i = 0; i < users.size(); i++) {
            User item = users.get(0);
            item.setId(789L);
        }
        System.out.println(users);
    }


    @Test
    public void t1() {
        LinkedList list = new LinkedList();
        list.add("A");
        list.add(2,"B");
        String s = (String) list.get(1);
        System.out.println(s);
    }


    @Test
    public void unmodifiableTest() {
        List<User> userList = getList();
        userList.add(new User(33L, "123"));
    }

    public List<User> getList() {
        return Collections.unmodifiableList(list);
    }
}
